package com.ziyunying.weather.repository

import com.ziyunying.weather.api.QWeatherApi
import com.ziyunying.weather.common.utils.Logger
import com.ziyunying.weather.common.cache.WeatherCacheManager
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.qweather.sdk.response.weather.WeatherDailyResponse
import com.qweather.sdk.response.weather.WeatherNowResponse
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class WeatherRepository @Inject constructor(
    private val qWeatherApi: QWeatherApi,
    private val cacheManager: WeatherCacheManager
) {
    private val _weatherData = MutableLiveData<WeatherNowResponse?>()
    private val _weatherData7d = MutableLiveData<WeatherDailyResponse?>()
    val weatherDataNow: LiveData<WeatherNowResponse?> = _weatherData
    val weatherData7d: LiveData<WeatherDailyResponse?> = _weatherData7d

    fun fetchWeatherNow(location: String) {
        qWeatherApi.fetchWeatherNow(
            location = location,
            onSuccess = { response ->
                Logger.logResponse(response, "今日的实时天气")
                _weatherData.postValue(response)
            },
            onFailure = { error -> Logger.logResponse(error) },
            onException = { e -> Logger.logResponse(e) }
        )
    }

    fun fetchWeather7d(location: String) {
        // 首先检查缓存
        val cachedData = cacheManager.getWeather7dData(location)
        if (cachedData != null) {
            Logger.logResponse(cachedData, "七天天气预报（来自缓存）")
            _weatherData7d.postValue(cachedData)
            return
        }
        
        // 检查今天是否已经请求过
        if (cacheManager.hasTodayWeather7dCache(location)) {
            Logger.logResponse(null, "今天已经请求过7天天气预报，请明天再试")
            return
        }
        
        // 从网络获取数据
        qWeatherApi.fetchWeather7d(
            location = location,
            onSuccess = { response ->
                response?.let {
                    // 保存到缓存
                    cacheManager.saveWeather7dData(location, it)
                    Logger.logResponse(it, "七天天气预报（来自网络）")
                    _weatherData7d.postValue(it)
                }
            },
            onFailure = { error -> 
                Logger.logResponse(error)
            },
            onException = { e -> 
                Logger.logResponse(e)
            }
        )
    }
    
    /**
     * 强制刷新7天天气预报（清除缓存后重新请求）
     */
    fun forceRefreshWeather7d(location: String) {
        cacheManager.clearWeather7dCache(location)
        fetchWeather7d(location)
    }
    
    /**
     * 检查今天是否已经请求过7天天气预报
     */
    fun hasTodayRequested7d(location: String): Boolean {
        return cacheManager.hasTodayWeather7dCache(location)
    }
}
